var call_submit_back_flag = false; //是否数据提交之后回调函数
var myCodeFrom; //表单验证对象
var obj_position = '';

$(function(){
	var load_write_index = '';
	var getInfoObj=function(){
		return 	$(this).parents("dd").find('.info');
	}
	$("[datatype]").focusin(function(){
		if(this.timeout){clearTimeout(this.timeout);}
		var infoObj=getInfoObj.call(this);
		if(infoObj.siblings(".Validform_right").length!=0){
			return;	
		}
		infoObj.show().siblings().hide();
		
	}).focusout(function(){
		var infoObj=getInfoObj.call(this);
		this.timeout=setTimeout(function(){
			infoObj.hide().siblings(".Validform_wrong,.Validform_loading").show();
		},0);
		
	});
	//绑定
	$("form[name='myfromSubmit']").each( function() {
		var ignoreHidden = $(this).attr('ignoreHidden') == undefined ? false : true;
		var ajaxPost = $(this).attr('ajaxPost') == undefined ? true : false;
		myCodeFrom = $(this).Validform({
			tiptype:4,
			ajaxPost:ajaxPost,
			ignoreHidden:ignoreHidden,
			beforeSubmit:function(curform){
				if( ajaxPost === true ) {
					curform.attr('request_type') != undefined ? obj_position = curform.attr('request_type') : '';
					if( curform.attr('fun_call') != undefined ) {
						var result = eval( curform.attr('fun_call') )();
						if( result === false ) return false;
					}
					load_write_index = waitload('正在努力加载...');
				}
			},
			callback:function(data){
				if( ajaxPost === true ) {
					if( obj_position == 'parent') {
						parent.zeroModal.close( load_write_index );
					} else {
						zeroModal.close( load_write_index );
					}
					if(data.status == '1'){
						success( data.info ,function( opt ){
							if( data.url != '') {
								if( obj_position == 'parent') {
									parent.location.href = data.url;
								} else {
									location.href = data.url;
								}
							} else {
								if(call_submit_back_flag === true){
									call_submit_back_func(data); //回调函数
								}
								obj_position = '';
							}
						});
					}else if( data.info != null ) {
						error( data.info );
						obj_position = '';
					} else {
						error( "操作失败，请重新操作" );
						obj_position = '';
					}
				}
			}
		})
	});
});

$(document).on( 'click' , '[menu="tip_menu"]',function(){
	var _self = $(this);
	var tc_index = zeroModal.confirm(_self.attr('title'), function() {
		//判断是否是ajax请求
		if( _self.attr('request_type') == 'ajax' ) {
			var load_text = _self.attr('load_txt');
			if( load_text == '' || load_text == undefined ) {
				load_text = '正在加载，请稍后...'
			}
			zeroModal.close(tc_index);
			var wait_index = waitload( load_text );
			$.get(_self.attr('href'),function(data){
				zeroModal.close(wait_index);
				if( data.status == 1 ) {
					success(data.info,function(opt){ 
						if( _self.attr('call_func') != undefined ) {
							eval( _self.attr('call_func') )( _self , data );
						} else {
							location.reload();
						}
					});
				} else {
					error( data.info );
				}
			},'json');
		} else {
			location.href = _self.attr( 'href' );
		}
	});
	return false;

});

$(document).on('click' , '[menu="load_iframe_url"]',function(){
	var _self = $(this);
	var _height = _self.attr('height') == undefined ? '60%' : _self.attr('height');
	var _width = _self.attr('width') == undefined ? '60%' : _self.attr('width');
	var _url = _self.attr('href');
	if( _self.attr('backfunc') != undefined && _self.attr('backfunc') != '') {
		eval( _self.attr('backfunc') )( _self );
	}
	zeroModal.show({
		title: _self.attr('title'),
		iframe: true,
		url: _url,
		esc: true,
		width: _width,
		height: _height
	});
	return false;
});

function success( info , funOk ){
	if( funOk == undefined ) {
		funOk = function(opt) {
			
		}
	}
	var data_obj = {
		content: info,
		buttons: [
			{ className: 'zeromodal-btn zeromodal-btn-primary', name: '确认', fn:funOk}
		]
	};
	
	if( obj_position == 'parent') {
		return parent.zeroModal.success( data_obj );
	} else {
		return zeroModal.success( data_obj );
	}
}

function error( info , funOk ){
	if( funOk == undefined ) {
		funOk = function(opt) {
			
		}
	}
	var data_obj = {
		content: info,
		buttons: [
			{ className: 'zeromodal-btn zeromodal-btn-primary', name: '确认', fn:funOk}
		]
	};
	
	if( obj_position == 'parent') {
		return parent.zeroModal.error( data_obj );
	} else {
		return zeroModal.error( data_obj );
	}
}

function waitload( data ){
	var data_obj =  {
		transition : true,
		closeBut:false,
		width : '400px',
		height : '150px',
		content : '<div style="width:100%;text-align:center;">'+data+'<div class="loader-inner ball-pulse" style=" margin:30px 0px 10px 0px;"><div></div><div></div><div></div><div></div></div></div>'
	};
	
	if( obj_position == 'parent') {
		return parent.zeroModal.show( data_obj );
	} else {
		return zeroModal.show( data_obj );
	}
}

function init_upload(objectName , title){
	title == null ? title = '选择上传的图片' : '';
	var _self = $("#"+objectName);
	_self.addClass('up_file_cont');
	var data_value = _self.attr('data-value') ? _self.attr('data-value') : '';
	var up_name = _self.attr('data-name') ? _self.attr('data-name') : 'photo';
	var up_type = _self.attr('data-type') ? _self.attr('data-type') : false;
	var is_check = _self.attr('data-check') ? _self.attr('data-check') : false;
	up_type ? up_name+='[]' : '';
	var template = '<div class="but_files"><input id="file_upload_'+objectName+'" name="file_upload" type="file" multiple="true"></div> <div class="tip_file_txt"> 请上传 {@width} * {@height} 不大于{@size}MB的图片</div>'+
	'<div class="file_img_lists"><dl id="'+objectName+'_list"  style="margin:0px;">';
	if( data_value != '' ) {
		data_value = data_value.split( ',' );
		$.each(data_value , function( k , v ){
			template += "<dd><a href=\"javascript:;\" class=\"img_upload_close\" onclick=\"img_upload_close(this)\">×</a><img src='" + v + "'><input type='hidden' value='" + v + "' name='" + up_name + "' /></dd>";
		});
	}
	template += '</dl>';
	if( is_check !== false ) {
		template += '<input type="hidden" id="pic_checked" ';
		if( data_value != '' ) {
			template += ' value="1" ';
		}
		template += ' nullmsg="请选择您要上传的图片" datatype="*"/>';
	}
	template += '</div>';
	var template_load = '<dd id="${fileID}"><a href="javascript:;" class="img_upload_close" onclick="img_upload_close(this)">×</a>'+
				'<div class="swf_up_num_s">已上传 0%</div>'+
				'<img src="'+STATIC_URL+'/images/loading.gif">'+
				'<input type="hidden" value="" name="'+up_name+'" />'+
				'<div class="load_int_shu">'+
					'<div class="load_int_she"></div>'+
				'</div>'+
			'</dd>';
	var size = _self.attr('data-size') ? _self.attr('data-size') : 2;
	_self.html(template.replace(/{@width}/g,_self.attr('data-width')).replace(/{@size}/g,size).replace(/{@height}/g,_self.attr('data-height')));
	_self.find("#file_upload_"+objectName).uploadify({
		'fileTypeDesc' : '不超过'+size+'M的图片 (*.gif;*.jpg;*.png)',
		'fileTypeExts'  : '*.jpg;*.png;*.gif',
		'multi'    : up_type,
		'fileSizeLimit': size * 1024000,
		'swf'      : STATIC_URL + 'js/uploadify/uploadify.swf',
		'uploader' : FILE_UPLOAD_URL,
		'queueSizeLimit' : 999,
		'buttonText' : title,
		'height' : 35,
		'queueID' : objectName+'_list',
		'width' : 110,
		'removeCompleted' : false,
		'postData' : {},
		'itemTemplate' : template_load,
		'timeoutuploadLimit' : 999,
		onSelectError : function (file, errorCode, errorMsg){
			alert(errorMsg);
		},
		onUploadProgress : function(file,fileBytesLoaded,fileTotalBytes,queueBytesLoaded,swfuploadifyQueueUploadSize) {
			_self.find('.file_img_lists').css({'margin' : '10px'});
			up_type ? '' : $("#"+file.id).prevAll().remove();
			var num = parseInt(fileBytesLoaded / file.size  * 100);
			$("#"+file.id+" div.load_int_she").css('width',num+'%');
			$("#"+file.id+" div.swf_up_num_s").html("已上传 " + num + ' %');
			if(fileBytesLoaded >= file.size ){
				$("#"+file.id+" div.swf_up_num_s").css('color','#fff').text("上传成功");
				$("#"+file.id+" div.load_int_she").css('width','100%');
			}
		},
		onUploadSuccess : function (file,data,response){
			if( _self.find('.Validform_checktip').length > 0 ) {
				_self.find('#pic_checked').val('1');
				_self.find('.Validform_wrong').text('').removeClass('Validform_wrong');
			}
			var data = eval('(' + data + ')');
			if(data.code != 200){
				alert(data.msg);
				return false;
			}
			data = data.data;
			$("#"+file.id+" img").attr('src',data.path);
			$("#"+file.id+" input").val(data.path);
		}
	});
}
function init_upload1(objectName , title){
	title == null ? title = '选择上传的文件' : '';
	var _self = $("#"+objectName);
	_self.addClass('up_file_cont');
	var data_value = _self.attr('data-value') ? _self.attr('data-value') : '';
	var up_name = _self.attr('data-name') ? _self.attr('data-name') : 'photo';
	var up_type = _self.attr('data-type') ? _self.attr('data-type') : false;
	var is_check = _self.attr('data-check') ? _self.attr('data-check') : false;
	up_type ? up_name+='[]' : '';
	var template = '<div class="but_files"><input id="file_upload_'+objectName+'" name="file_upload" type="file" multiple="true"></div> <div class="tip_file_txt"> 请上传 {@width} * {@height} 不大于{@size}MB的图片</div>'+
	'<div class="file_img_lists"><dl id="'+objectName+'_list"  style="margin:0px;">';
	if( data_value != '' ) {
		data_value = data_value.split( ',' );
		$.each(data_value , function( k , v ){
			template += "<dd style='width:380px;margin-right:40px;' ><a href=\"javascript:;\" class=\"img_upload_close\"  style=\"margin-left:380px;\" onclick=\"img_upload_close(this)\">×</a><input type='text' value='" + v + "' name='" + up_name + "' /></dd>";
		});
	}
	template += '</dl>';
	if( is_check !== false ) {
		template += '<input type="hidden" id="pic_checked" ';
		if( data_value != '' ) {
			template += ' value="1" ';
		}
		template += ' nullmsg="请选择您要上传的图片" datatype="*"/>';
	}
	template += '</div>';
	var template_load = '<dd id="${fileID}" style="width:380px;margin-right:40px;"><a href="javascript:;" class="img_upload_close" style="margin-left:380px;" onclick="img_upload_close(this)">×</a>'+
				'<span>资料</span><input type="text" value="" name="'+up_name+'" />'+
			'</dd>';
	var size = _self.attr('data-size') ? _self.attr('data-size') : 2;
	_self.html(template.replace(/{@width}/g,_self.attr('data-width')).replace(/{@size}/g,size).replace(/{@height}/g,_self.attr('data-height')));
	_self.find("#file_upload_"+objectName).uploadify({
		'fileTypeDesc' : '不超过'+size+'M的图片 (*.gif;*.jpg;*.png)',
		'fileTypeExts'  : '*.jpg;*.png;*.gif;*.txt',
		'multi'    : up_type,
		'fileSizeLimit': size * 1024000,
		'swf'      : STATIC_URL + 'js/uploadify/uploadify.swf?var='+ Math.random(),
		'uploader' : FILE_UPLOAD_URL,
		'queueSizeLimit' : 999,
		'buttonText' : title,
		'height' : 35,
		'queueID' : objectName+'_list',
		'width' : 110,
		'removeCompleted' : false,
		'postData' : {},
		'itemTemplate' : template_load,
		'timeoutuploadLimit' : 999,
		onSelectError : function (file, errorCode, errorMsg){
			alert(errorMsg);
		},
		onUploadSuccess : function (file,data,response){
			if( _self.find('.Validform_checktip').length > 0 ) {
				_self.find('#pic_checked').val('1');
				_self.find('.Validform_wrong').text('').removeClass('Validform_wrong');
			}
			var data = eval('(' + data + ')');
			if(data.code != 200){
				alert(data.msg);
				return false;
			}
			data = data.data;
//			$("#"+file.id+" img").attr('src',data.path);
			$("#"+file.id+" input").val(data.path);
		}
	});
}
function img_upload_close( obj ) {
	$(obj).closest('dd').remove();
}


//百度地图管理

   /**
          * 
          * 选择城市start
          */
	function theLocation(){
		var city = $("#city  option:selected").text();
                
		if(city != ""){
			map.centerAndZoom(city,11);      // 用城市名设置地图中心点
		}
	}
         /**
          * 
          * 选择城市end
          */
        
        
	 /**
          * 
          * 输入地址start
          */
	function searchLocation(){
            var site = $("#address").val();
            var option = {
                    onSearchComplete: function(results){
                            if (local.getStatus() == BMAP_STATUS_SUCCESS){
                                    if(results.getCurrentNumPois()){
                                            map.centerAndZoom(results.getPoi(0).point,15);
                                            $("#lng").val(results.getPoi(0).point.lng);
                                            $("#lat").val(results.getPoi(0).point.lat);
                                             bImg(results.getPoi(0).point.lng,results.getPoi(0).point.lat);
                                    }
                            }else{
                                  $("#address").val('');
                                    alert("改地址输入不存在，请重新输入！");
                            }
                    }
            };
            var local = new BMap.LocalSearch(map,option);
            local.search(site);
    }
        /**
          * 
          * 输入地址end
          */
         
    //点击地图事件start
	function showInfo(e){
            $("#lng").val(e.point.lng);
            $("#lat").val(e.point.lat);
            bImg(e.point.lng,e.point.lat)
	}
	
    //点击地图事件end
    
    //图标
    
    function bImg(lng,lat){
         var point = new BMap.Point(lng,lat);
            map.clearOverlays();
            var marker = new BMap.Marker(point);  // 创建标注
            map.addOverlay(marker);               // 将标注添加到地图中
            marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    }
	
	function formatMoney(number, places, symbol, thousand, decimal) {
		number = number || 0;
		places = !isNaN(places = Math.abs(places)) ? places : 2;
		symbol = symbol !== undefined ? symbol : "$";
		thousand = thousand || ",";
		decimal = decimal || ".";
		var negative = number < 0 ? "-" : "",
			i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
			j = (j = i.length) > 3 ? j % 3 : 0;
		return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
	}
	
	function datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
		var dateSpan,
			tempDate,
			iDays;
		sDate1 = Date.parse(sDate1);
		sDate2 = Date.parse(sDate2);
		dateSpan = sDate2 - sDate1;
		dateSpan = Math.abs(dateSpan);
		iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
		return iDays
	};